export function useReadStream() {
  /** 读取流信息 */
  async function handleStreamResponse(
    response: any,
    onMessage: (jsonData: any) => void
  ) {
    const reader = response.body.getReader();
    const decoder = new TextDecoder();
    let done = false;
    let buffer = "";
    while (!done) {
      const { value, done: isDone } = await reader.read();
      done = isDone;
      buffer += decoder.decode(value, { stream: true });
      if (!buffer.includes("\n")) continue;
      const messages = buffer.split("\n");
      for (const message of messages) {
        const jsonStr = message.replace(/^\s*data: \s*/, "").trim();
        if (jsonStr !== "[DONE]") {
          if (jsonStr === "") continue;
          try {
            const jsonData = JSON.parse(jsonStr);
            onMessage(jsonData);
          } catch (e) {
            console.log(e, "error");
          }
        } else {
          done = true;
        }
      }
      buffer = "";
    }
  }

  return {
    handleStreamResponse,
  };
}
